<template>
  <div class="address">
    <div class="content">
      <div class="con-box">
        <div class="add-address">
          <a href="javascript:;" class="add-btn" @click="handleAdd"
            >新增收货地址</a
          >
          <div class="add-limit">
            你已创建<span class="number">{{ addressDataLen }}</span
            >个收货地址，最多可创建<span class="number">6</span>个
          </div>
        </div>
        <div class="address-list">
          <div
            class="item"
            :class="{ 'default-address': addr.isDefault }"
            v-for="addr in addressData"
            :key="addr._id"
          >
            <div class="item-row">
              <div class="name">{{ addr.receiver }}</div>
              <div class="phone-number">{{ addr.mobile }}</div>
              <a href="javascript:;" class="default-btn" v-if="addr.isDefault"
                >默认</a
              >
              <a
                href="javascript:;"
                class="default-btn"
                v-else
                @click="setDefault(addr._id)"
                >设为默认</a
              >
              <div class="action-box">
                <span class="edit" @click="handleEdit(addr)"></span>
                <el-popconfirm
                  title="你确定要删除该收货地址吗?"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  @confirm="handleDelete(addr._id)"
                >
                  <template #reference>
                    <span class="delete"></span>
                  </template>
                </el-popconfirm>
              </div>
            </div>
            <div class="address-detail">
              {{ addr.province }} {{ addr.city }} {{ addr.area }}{{ addr.addr }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 收货地址表单 -->
    <el-dialog
      v-model="dialogVisable"
      title="新增收件人信息"
      width="35%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form :model="form" ref="formRef" :rules="rules">
        <el-form-item prop="receiver" label="收件人：" style="margin-left: 14px">
          <el-input v-model.trim="form.receiver"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号码：">
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
        <el-form-item label="所在地区：">
          <div style="display: flex">
            <el-select
              v-model="form.province"
              @change="handleChange1"
              class="area"
              placeholder="请选择"
              no-data-text="无数据"
            >
              <el-option
                :label="p.name"
                :value="p.code"
                v-for="p in provinceData"
                :key="p._id"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="form.city"
              class="area"
              @change="handleChange2"
              placeholder="请选择"
              no-data-text="无数据"
            >
              <el-option
                :label="c.name"
                :value="c.code"
                v-for="c in cityData"
                :key="c._id"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="form.area"
              class="area"
              placeholder="请选择"
              no-data-text="无数据"
              ><el-option
                :label="a.name"
                :value="a.code"
                v-for="a in areaData"
                :key="a._id"
              ></el-option
            ></el-select>
          </div>
        </el-form-item>
        <el-form-item prop="addr" label="详细地址：">
          <el-input v-model.trim="form.addr"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisable = false">取消</el-button>
          <el-button type="primary" @click="save">保存收件人信息</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="address">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import {
  reqProvinceData,
  reqCityData,
  reqAreaData,
  reqAddressList,
  addAddress,
  updateAddress,
  deleteAddress,
  setDefaultAddr,
} from "@/api/address";
import useUserStore from "@/stores/modules/user";
import { ElMessage } from "element-plus";

let userId = useUserStore().user._id;
let dialogVisable = ref(false);
// 表单实例
let formRef = ref<any>();
// 地址数据
const addressData = ref<any>([]);
// 地址数据个数
const addressDataLen = computed(() => addressData.value.length);
// 省数据
let provinceData = ref<any>([]);
// 市
let cityData = ref<any>([]);
// 区
let areaData = ref<any>([]);
// 收货地址表单
let form = reactive<any>({
  _id: "",
  receiver: "",
  mobile: "",
  province: "",
  city: "",
  area: "",
  addr: "",
  isDefault: false,
});

// 新增收货地址回调
const handleAdd = () => {
  if (addressDataLen.value >= 6) {
    ElMessage.warning("最多可创建6个收货地址!");
    return;
  }
  dialogVisable.value = true;
  reset();
};

// 点击修改按钮
const handleEdit = (addr: any) => {
  dialogVisable.value = true;
  Object.assign(form,JSON.parse(JSON.stringify(addr)))
};

// 点击删除按钮的回调
const handleDelete = async (_id: any) => {
  let result = await deleteAddress(_id);
  if (result.code == 200) {
    ElMessage.success(result.msg);
    getAddressInfo();
  } else {
    ElMessage.error(result.msg);
  }
};

// 点击保存按钮的回调
const save = async () => {
  await formRef.value.validate();
  if(!form.province || !form.city || !form.area ){
    ElMessage.warning("请输入完整地区信息！")
    return
  }
  // 新增
  if (!form._id) {
    let data = Object.assign(form,{userId})
    let result = await addAddress(data);
    if (result.code == 200) {
      dialogVisable.value = false;
      ElMessage.success(result.msg);
      getAddressInfo();
    } else {
      ElMessage.error(result.msg);
    }
  } else {
    // 修改
    let result = await updateAddress(form);
    if (result.code == 200) {
      dialogVisable.value = false;
      ElMessage.success(result.msg);
      getAddressInfo();
    } else {
      ElMessage.error(result.msg);
    }
  }
};

// 设置默认地址
const setDefault = async (id: any) => {
  let result = await setDefaultAddr({ userId, _id: id });
  if (result.code == 200) {
    ElMessage.success(result.msg);
    getAddressInfo();
  } else {
    ElMessage.error(result.msg);
  }
};

// 获取地址列表
const getAddressInfo = async () => {
  let result = await reqAddressList(userId);
  if (result.code == 200) {
    addressData.value = result.data;
  } else {
    ElMessage.error(result.msg);
  }
};

const reset = () => {
  Object.assign(form, {
    _id: "",
    receiver: "",
    mobile: "",
    province: "",
    city: "",
    area: "",
    addr: "",
    isDefault: false,
  });
};

const handleChange1 = () => {
  form.city = "";
  form.area = "";
  getCityData();
};

const handleChange2 = () => {
  form.area = "";
  getAreaData();
};

// 获取省数据
const getProvinceData = async () => {
  let result = await reqProvinceData();
  if (result.code == 200) {
    provinceData.value = result.data;
  } else {
    ElMessage.error(result.msg);
  }
};

// 获取市数据
const getCityData = async () => {
  let result = await reqCityData(form.province);
  if (result.code == 200) {
    cityData.value = result.data;
  } else {
    ElMessage.error(result.msg);
  }
};

// 获取区数据
const getAreaData = async () => {
  let result = await reqAreaData(form.city);
  if (result.code == 200) {
    areaData.value = result.data;
  } else {
    ElMessage.error(result.msg);
  }
};

// 手机号
const validatePhone = (rule: any, value: any, callback: any) => {
  if (!/^1[3456789]\d{9}$/.test(value)) {
    callback(new Error("请输入正确的手机号"));
  } else {
    callback();
  }
};
// 详细地址
const validateAddr = (rule: any, value: any, callback: any) => {
  if (!value && value.length < 5) {
    callback(new Error("详细地址不能少于5个字"));
  } else {
    callback();
  }
};
// 收件人
const validateReceiver = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请输入收件人"));
  } else {
    callback();
  }
};
// 校验规则
const rules = {
  receiver:[{validator:validateReceiver,trigger: "blur"}],
  mobile: [{ validator: validatePhone, trigger: "blur" }],
  addr:[{validator: validateAddr, trigger: "blur" }]
};

onMounted(() => {
  getAddressInfo();
  getProvinceData();
});
</script>

<style lang="scss" scoped>
.address {
  min-height: 505px;
  padding-bottom: 40px;
  font-size: 12px;
  .content {
    display: flex;
    width: 1080px;
    margin: auto;
    .con-box {
      flex: 1;
      margin-top: 30px;
      .add-address {
        display: flex;
        padding-top: 5px;
        align-items: center;
        .add-btn {
          padding: 5px 15px;
          background: #e1251b;
          color: #fff;
          border-radius: 2px;
          margin-right: 10px;
          text-decoration: none;
          &:hover {
            text-decoration: none;
          }
        }
        .add-limit {
          color: #999;
          .number {
            color: #e1251b;
            margin: 0 3px;
          }
        }
      }
      .address-list {
        .item {
          margin-top: 20px;
          border: 1px solid #eee;
          padding: 15px 20px;
          transition: all 0.2s;
          cursor: pointer;
          &:hover {
            border-color: #e1251b;
            .item-row {
              .default-btn {
                display: block;
              }
              .action-box {
                display: block;
              }
            }
          }
          .item-row {
            display: flex;
            align-items: center;
            .name {
              font-size: 14px;
              font-family: arial;
              margin-right: 20px;
            }
            .phone-number {
              font-size: 14px;
              font-family: arial;
              margin-right: 20px;
            }
            .default-btn {
              color: #005ea7;
              text-decoration: none;
              display: none;
              &:hover {
                text-decoration: none;
                color: #e1251b;
              }
            }
            .action-box {
              flex: 1;
              text-align: right;
              display: none;
              .edit {
                margin-right: 10px;
                display: inline-block;
                width: 14px;
                height: 14px;
                background: url(../../assets/icons.d354c61.png) 0 -434px no-repeat;
                cursor: pointer;
                &:hover {
                  background-position: -19px -434px;
                }
              }
              .delete {
                display: inline-block;
                width: 14px;
                height: 14px;
                background: url(../../assets/icons.d354c61.png) 0 -415px no-repeat;
                cursor: pointer;
                &:hover {
                  background-position: -19px -415px;
                }
              }
            }
          }
          .address-detail {
            color: #999;
            margin-top: 10px;
          }
        }
        .item.default-address {
          .default-btn {
            display: block;
            background: #e1251b;
            color: #fff;
            padding: 0 3px;
            border-radius: 2px;
            &:hover {
              text-decoration: none;
              color: #fff;
            }
          }
        }
      }
    }
  }
  .area {
    display: inline-block;
    height: 20px;
    line-height: 20px;
    width: 125px;
    margin-right: 10px;
    position: relative;
  }
}
</style>
